import * as vscode from 'vscode';
import { parseStr, format } from './lib';



export const init = (context: vscode.ExtensionContext) => {
  let disposable = vscode.commands.registerCommand('csstips.helloWorld', () => {
		vscode.window.showInformationMessage('Hello World from csstips!');
	});
	context.subscriptions.push(disposable);

	const onSave = vscode.workspace.onWillSaveTextDocument(event=>{
		const formatOnSave = vscode.workspace.getConfiguration().get('cssTips.formatOnSave') as Boolean;
		
		if(formatOnSave === false){
			return undefined;
		}
		const fileName = event.document.fileName;
		if(/(\.html|\.vue|\.css|\.less|\.scss)$/.test(fileName)){
			// 末尾追加换行符
			let eol = '';
			let rex = /(.|\n|\r)*/g;
			// 如果是style标签内书写css 则需要特殊处理
			if(/(\.html|\.vue)$/.test(fileName)){
				eol = '\n';
				rex = /(?<=<style.*>)(.|\n|\r)*(?=<\/style>)/g;
			}

			event.waitUntil(new Promise((resolve,reject) => {
				const text = event.document.getText();
				const lines = event.document.lineCount;
				const endLine = event.document.lineAt(lines - 1);
				const start = new vscode.Position(0, 0);
				const end = new vscode.Position(lines - 1, endLine.text.length);
		
				
				const newText = text.replace(rex, s =>{
					// if( s.match(/{/g)?.length !== s.match(/}/g)?.length) {
					// 	return s;
					// }
					const ast = parseStr(s);
					let start = 0;
					if(/(\.html)$/.test(fileName)){
						start = 1;
					}
					let sss = format(ast, start);
					return eol + sss + eol;
				});
				const dt =	vscode.TextEdit.replace(new vscode.Range(start, end), newText);
				resolve([dt]);
				
			}));
		}
		
	});
	context.subscriptions.push(onSave);
};